Установка R, R studio

www.cran.r-project.org # Оффициальный сайт R (содержит всю необходимую информацию для R, в тч и саму программу :) )

# на Оф сайте R можно найти и литературу и прочие полезные вещи
# www.rstudio.com # приложение rstudio (desktop version -  всеми любимая бесплатная # версия программы:))
# Если вы дочитали до этой строки, то уже заметили, что некоторый текст выделяется # зеленым цветом или любым другим в зависимости от цветового оформления 
# коментарии в R выделяются '#' Важно: весь текст после этого символа не будет 
# восприниматься как программа

Очень полезно оставлять комментарии относительно кода. Это помогает вспомнить зачем эти строки писались и какое их предназначение. Также это бывает полезно для других разработчиков. Не всегда они поймут зачем вы это понаписали.

Настройки для R studio, без которых сложно жить

Tools-Global options-General

Restore .Rdata into workspace at startup - галочка отсутствует

save workspace to .Rdata on Exit - never

Tools-Global options - Sweave - weave .Rnw files using - knitr

Tools-Global options- Code-Diagnostics : Везде галочки:)

Первые шаги работы лучше начинать с определения места храниения информации

getwd() # Показывает директорию сохраниения файлов работы в Rstudio
## [1] "/Users/mishkail/r/R1"

Давайте установим другую дирректорию в качестве рабочей!

setwd("/Users/mishkail/R")

Или, создадим свою директорию с блек джеком и удобным размещением!!!

dir.create("/Users/mishkail/R/R1") # и, не медля ни минуты, установим ее рабочей
## Warning in dir.create("/Users/mishkail/R/R1"): '/Users/mishkail/R/R1' уже
## существует
setwd("/Users/mishkail/R/R1")

Проверим!

  getwd()
## [1] "/Users/mishkail/r/R1"

Проверим, что же у нас в текущей директории

list.files()
##  [1] "1"             "h1"            "history1"      "R!.R"         
##  [5] "R1.html"       "R1.Rmd"        "R1.tex"        "R1H.rtf"      
##  [9] "S1.R"          "Untitled.docx" "Untitled.Rmd"  "Untitled.tex"

R - обьктно ориентированный язык программирования, по большей части, направленный на статистические исследования,

широко используется в области биостатистики, data science ( machine learning, neural networks), и тд ## Важно понимать, что в основе R лежит создание обьектов и работа с ними

Базовые классы в R:

Основной обьект в R - вектор (vector)

Важно помнить, что вектор может содержать значения одного класса данных Но есть исключение - это список (list) Список может содержать разные классы значений Список чаще всего используется именно по причине создания вектора, содержащего разные классы значений

Первая команда!

z<-'hello,world'
z
## [1] "hello,world"

Когда мы вводим название созданного обьекта и нажимаем enter то получаем результат этого объекта В R это называется autoprinting По сути мы можем использовать команду print и получим также значение объекта z

print(z)
## [1] "hello,world"

Autoprinting удобная характеристика для упрощения работы, используемая в R

R-передовой калькулятор, который не надо создавать:)

Как известно

2+2
## [1] 4

Вычитаем аналогичным способом

2-2
## [1] 0

Как известно Вычитание - это частный случай сложения:) Давайте проверим

2+(-2)
## [1] 0

С умножением и делением ситуация аналогичная

6*2/3
## [1] 4

R знает правильный порядок математических действий!

  2+3*3
## [1] 11

Степени и корни также легко реализуемы

2^3
## [1] 8
23^54 # та степень которую в уме считать чуть сложнее
## [1] 3.414312e+73

Проверим корень

3.414312e+73^(1/54) # Можем не расшифровывать такие большие числа и поверить R на слово
## [1] 23

Квадратный корень чуть проще

sqrt(25) # корень 25 для слабаков:) Зачем нам R если мы не можем найти корень, например, числа 2546243
## [1] 5
sqrt(2546243) # легко:)
## [1] 1595.695

А что известно про число ПИ? 3.14159….. А если нам нужен корень? А если я забыл про ПИ?

sqrt(pi)
## [1] 1.772454
pi # можно его просто вспомнить
## [1] 3.141593
factorial(3)
## [1] 6

Более сложные выражения требуют нескольких действий

a <- factorial(5)# создаем переменную, которая посчитает факториал 5 
b <- choose(n=5,k=3)# создаем переменную, которая подсчитает для нас количество комбинаций
sqrt(a + b) # а теперь возьмем корень из суммы этих чисел:)
## [1] 11.40175
log(factorial(5)+choose(n=5,k=3)) # Хотя можно прописывать и одной строкой и взять, наконец десятичный логарифм, а не корень:) 
## [1] 4.867534

При тяжелых и энергоемких расчетах, введение переменных облегчает работу и проверку кода

Логические выражения!

Проверим правдивость некоторых расчетов:) как известно:

2+2==4
## [1] TRUE

Важно! логический оператор требует двойного знака равно!

#2+2=4  Работать не будет (можно проверить)

Логическое значение TRUE FALSE говорят нам о соответствии или правдивости утверждения А ну ка посмотрим, что же больше?

2>2 
## [1] FALSE
100>2 # В такой записи достаточно одного знака
## [1] TRUE
0.4+0.3==0.7 # Знакомое равенство
## [1] TRUE
0.4-0.3==0.1  # Что-то новенькое:)
## [1] FALSE

Поработаем с векторами!

x<-5:10 # Создадим вектор
x
## [1]  5  6  7  8  9 10

он сохранился в нашей среде и мы можем с ним начать работать в любой момент

y<-c(1,3,6,8,10,3) # а здесь вектор из произвольных чисел

Построим график для каждого вектора

plot(x)

plot(y)

plot(x,y)

vec <- c('1 word', '2 word') # вектор нечисловых значений
vec
## [1] "1 word" "2 word"

небольшой пример возможностей от R

demo(graphics)
## 
## 
##  demo(graphics)
##  ---- ~~~~~~~~
## 
## > #  Copyright (C) 1997-2009 The R Core Team
## > 
## > require(datasets)
## 
## > require(grDevices); require(graphics)
## 
## > ## Here is some code which illustrates some of the differences between
## > ## R and S graphics capabilities.  Note that colors are generally specified
## > ## by a character string name (taken from the X11 rgb.txt file) and that line
## > ## textures are given similarly.  The parameter "bg" sets the background
## > ## parameter for the plot and there is also an "fg" parameter which sets
## > ## the foreground color.
## > 
## > 
## > x <- stats::rnorm(50)
## 
## > opar <- par(bg = "white")
## 
## > plot(x, ann = FALSE, type = "n")

## 
## > abline(h = 0, col = gray(.90))
## 
## > lines(x, col = "green4", lty = "dotted")
## 
## > points(x, bg = "limegreen", pch = 21)
## 
## > title(main = "Simple Use of Color In a Plot",
## +       xlab = "Just a Whisper of a Label",
## +       col.main = "blue", col.lab = gray(.8),
## +       cex.main = 1.2, cex.lab = 1.0, font.main = 4, font.lab = 3)
## 
## > ## A little color wheel.    This code just plots equally spaced hues in
## > ## a pie chart.    If you have a cheap SVGA monitor (like me) you will
## > ## probably find that numerically equispaced does not mean visually
## > ## equispaced.  On my display at home, these colors tend to cluster at
## > ## the RGB primaries.  On the other hand on the SGI Indy at work the
## > ## effect is near perfect.
## > 
## > par(bg = "gray")
## 
## > pie(rep(1,24), col = rainbow(24), radius = 0.9)

## 
## > title(main = "A Sample Color Wheel", cex.main = 1.4, font.main = 3)
## 
## > title(xlab = "(Use this as a test of monitor linearity)",
## +       cex.lab = 0.8, font.lab = 3)
## 
## > ## We have already confessed to having these.  This is just showing off X11
## > ## color names (and the example (from the postscript manual) is pretty "cute".
## > 
## > pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)
## 
## > names(pie.sales) <- c("Blueberry", "Cherry",
## +              "Apple", "Boston Cream", "Other", "Vanilla Cream")
## 
## > pie(pie.sales,
## +     col = c("purple","violetred1","green3","cornsilk","cyan","white"))

## 
## > title(main = "January Pie Sales", cex.main = 1.8, font.main = 1)
## 
## > title(xlab = "(Don't try this at home kids)", cex.lab = 0.8, font.lab = 3)
## 
## > ## Boxplots:  I couldn't resist the capability for filling the "box".
## > ## The use of color seems like a useful addition, it focuses attention
## > ## on the central bulk of the data.
## > 
## > par(bg="cornsilk")
## 
## > n <- 10
## 
## > g <- gl(n, 100, n*100)
## 
## > x <- rnorm(n*100) + sqrt(as.numeric(g))
## 
## > boxplot(split(x,g), col="lavender", notch=TRUE)

## 
## > title(main="Notched Boxplots", xlab="Group", font.main=4, font.lab=1)
## 
## > ## An example showing how to fill between curves.
## > 
## > par(bg="white")
## 
## > n <- 100
## 
## > x <- c(0,cumsum(rnorm(n)))
## 
## > y <- c(0,cumsum(rnorm(n)))
## 
## > xx <- c(0:n, n:0)
## 
## > yy <- c(x, rev(y))
## 
## > plot(xx, yy, type="n", xlab="Time", ylab="Distance")

## 
## > polygon(xx, yy, col="gray")
## 
## > title("Distance Between Brownian Motions")
## 
## > ## Colored plot margins, axis labels and titles.    You do need to be
## > ## careful with these kinds of effects.    It's easy to go completely
## > ## over the top and you can end up with your lunch all over the keyboard.
## > ## On the other hand, my market research clients love it.
## > 
## > x <- c(0.00, 0.40, 0.86, 0.85, 0.69, 0.48, 0.54, 1.09, 1.11, 1.73, 2.05, 2.02)
## 
## > par(bg="lightgray")
## 
## > plot(x, type="n", axes=FALSE, ann=FALSE)

## 
## > usr <- par("usr")
## 
## > rect(usr[1], usr[3], usr[2], usr[4], col="cornsilk", border="black")
## 
## > lines(x, col="blue")
## 
## > points(x, pch=21, bg="lightcyan", cex=1.25)
## 
## > axis(2, col.axis="blue", las=1)
## 
## > axis(1, at=1:12, lab=month.abb, col.axis="blue")
## 
## > box()
## 
## > title(main= "The Level of Interest in R", font.main=4, col.main="red")
## 
## > title(xlab= "1996", col.lab="red")
## 
## > ## A filled histogram, showing how to change the font used for the
## > ## main title without changing the other annotation.
## > 
## > par(bg="cornsilk")
## 
## > x <- rnorm(1000)
## 
## > hist(x, xlim=range(-4, 4, x), col="lavender", main="")

## 
## > title(main="1000 Normal Random Variates", font.main=3)
## 
## > ## A scatterplot matrix
## > ## The good old Iris data (yet again)
## > 
## > pairs(iris[1:4], main="Edgar Anderson's Iris Data", font.main=4, pch=19)

## 
## > pairs(iris[1:4], main="Edgar Anderson's Iris Data", pch=21,
## +       bg = c("red", "green3", "blue")[unclass(iris$Species)])

## 
## > ## Contour plotting
## > ## This produces a topographic map of one of Auckland's many volcanic "peaks".
## > 
## > x <- 10*1:nrow(volcano)
## 
## > y <- 10*1:ncol(volcano)
## 
## > lev <- pretty(range(volcano), 10)
## 
## > par(bg = "lightcyan")
## 
## > pin <- par("pin")
## 
## > xdelta <- diff(range(x))
## 
## > ydelta <- diff(range(y))
## 
## > xscale <- pin[1]/xdelta
## 
## > yscale <- pin[2]/ydelta
## 
## > scale <- min(xscale, yscale)
## 
## > xadd <- 0.5*(pin[1]/scale - xdelta)
## 
## > yadd <- 0.5*(pin[2]/scale - ydelta)
## 
## > plot(numeric(0), numeric(0),
## +      xlim = range(x)+c(-1,1)*xadd, ylim = range(y)+c(-1,1)*yadd,
## +      type = "n", ann = FALSE)

## 
## > usr <- par("usr")
## 
## > rect(usr[1], usr[3], usr[2], usr[4], col="green3")
## 
## > contour(x, y, volcano, levels = lev, col="yellow", lty="solid", add=TRUE)
## 
## > box()
## 
## > title("A Topographic Map of Maunga Whau", font= 4)
## 
## > title(xlab = "Meters North", ylab = "Meters West", font= 3)
## 
## > mtext("10 Meter Contour Spacing", side=3, line=0.35, outer=FALSE,
## +       at = mean(par("usr")[1:2]), cex=0.7, font=3)
## 
## > ## Conditioning plots
## > 
## > par(bg="cornsilk")
## 
## > coplot(lat ~ long | depth, data = quakes, pch = 21, bg = "green3")

## 
## > par(opar)

и еще один пример)

demo(persp)
## 
## 
##  demo(persp)
##  ---- ~~~~~
## 
## > ### Demos for  persp()  plots   -- things not in  example(persp)
## > ### -------------------------
## > 
## > require(datasets)
## 
## > require(grDevices); require(graphics)
## 
## > ## (1) The Obligatory Mathematical surface.
## > ##     Rotated sinc function.
## > 
## > x <- seq(-10, 10, length.out = 50)
## 
## > y <- x
## 
## > rotsinc <- function(x,y)
## + {
## +     sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }
## +     10 * sinc( sqrt(x^2+y^2) )
## + }
## 
## > sinc.exp <- expression(z == Sinc(sqrt(x^2 + y^2)))
## 
## > z <- outer(x, y, rotsinc)
## 
## > oldpar <- par(bg = "white")
## 
## > persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue")

## 
## > title(sub=".")## work around persp+plotmath bug
## 
## > title(main = sinc.exp)
## 
## > persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue",
## +       ltheta = 120, shade = 0.75, ticktype = "detailed",
## +       xlab = "X", ylab = "Y", zlab = "Z")

## 
## > title(sub=".")## work around persp+plotmath bug
## 
## > title(main = sinc.exp)
## 
## > ## (2) Visualizing a simple DEM model
## > 
## > z <- 2 * volcano        # Exaggerate the relief
## 
## > x <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)
## 
## > y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)
## 
## > persp(x, y, z, theta = 120, phi = 15, scale = FALSE, axes = FALSE)

## 
## > ## (3) Now something more complex
## > ##     We border the surface, to make it more "slice like"
## > ##     and color the top and sides of the surface differently.
## > 
## > z0 <- min(z) - 20
## 
## > z <- rbind(z0, cbind(z0, z, z0), z0)
## 
## > x <- c(min(x) - 1e-10, x, max(x) + 1e-10)
## 
## > y <- c(min(y) - 1e-10, y, max(y) + 1e-10)
## 
## > fill <- matrix("green3", nrow = nrow(z)-1, ncol = ncol(z)-1)
## 
## > fill[ , i2 <- c(1,ncol(fill))] <- "gray"
## 
## > fill[i1 <- c(1,nrow(fill)) , ] <- "gray"
## 
## > par(bg = "lightblue")
## 
## > persp(x, y, z, theta = 120, phi = 15, col = fill, scale = FALSE, axes = FALSE)

## 
## > title(main = "Maunga Whau\nOne of 50 Volcanoes in the Auckland Region.",
## +       font.main = 4)
## 
## > par(bg = "slategray")
## 
## > persp(x, y, z, theta = 135, phi = 30, col = fill, scale = FALSE,
## +       ltheta = -120, lphi = 15, shade = 0.65, axes = FALSE)

## 
## > ## Don't draw the grid lines :  border = NA
## > persp(x, y, z, theta = 135, phi = 30, col = "green3", scale = FALSE,
## +       ltheta = -120, shade = 0.75, border = NA, box = FALSE)

## 
## > ## `color gradient in the soil' :
## > fcol <- fill ; fcol[] <- terrain.colors(nrow(fcol))
## 
## > persp(x, y, z, theta = 135, phi = 30, col = fcol, scale = FALSE,
## +       ltheta = -120, shade = 0.3, border = NA, box = FALSE)

## 
## > ## `image like' colors on top :
## > fcol <- fill
## 
## > zi <- volcano[ -1,-1] + volcano[ -1,-61] +
## +            volcano[-87,-1] + volcano[-87,-61]  ## / 4
## 
## > fcol[-i1,-i2] <-
## +     terrain.colors(20)[cut(zi,
## +                            stats::quantile(zi, seq(0,1, length.out = 21)),
## +                            include.lowest = TRUE)]
## 
## > persp(x, y, 2*z, theta = 110, phi = 40, col = fcol, scale = FALSE,
## +       ltheta = -120, shade = 0.4, border = NA, box = FALSE)

## 
## > ## reset par():
## > par(oldpar)

и еще один самый последний пример))

demo(image)
## 
## 
##  demo(image)
##  ---- ~~~~~
## 
## > #  Copyright (C) 1997-2009 The R Core Team
## > 
## > require(datasets)
## 
## > require(grDevices); require(graphics)
## 
## > x <- 10*(1:nrow(volcano)); x.at <- seq(100, 800, by=100)
## 
## > y <- 10*(1:ncol(volcano)); y.at <- seq(100, 600, by=100)
## 
## >                    # Using Terrain Colors
## > 
## > image(x, y, volcano, col=terrain.colors(100),axes=FALSE)

## 
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="brown")
## 
## > axis(1, at=x.at)
## 
## > axis(2, at=y.at)
## 
## > box()
## 
## > title(main="Maunga Whau Volcano", sub = "col=terrain.colors(100)", font.main=4)
## 
## >                    # Using Heat Colors
## > 
## > image(x, y, volcano, col=heat.colors(100), axes=FALSE)

## 
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="brown")
## 
## > axis(1, at=x.at)
## 
## > axis(2, at=y.at)
## 
## > box()
## 
## > title(main="Maunga Whau Volcano", sub = "col=heat.colors(100)", font.main=4)
## 
## >                    # Using Gray Scale
## > 
## > image(x, y, volcano, col=gray(100:200/200), axes=FALSE)

## 
## > contour(x, y, volcano, levels=seq(90, 200, by=5), add=TRUE, col="black")
## 
## > axis(1, at=x.at)
## 
## > axis(2, at=y.at)
## 
## > box()
## 
## > title(main="Maunga Whau Volcano \n col=gray(100:200/200)", font.main=4)
## 
## > ## Filled Contours are even nicer sometimes :
## > example(filled.contour)
## 
## flld.c> require(grDevices) # for colours
## 
## flld.c> filled.contour(volcano, color = terrain.colors, asp = 1) # simple

## 
## flld.c> x <- 10*1:nrow(volcano)
## 
## flld.c> y <- 10*1:ncol(volcano)
## 
## flld.c> filled.contour(x, y, volcano, color = terrain.colors,
## flld.c+     plot.title = title(main = "The Topography of Maunga Whau",
## flld.c+     xlab = "Meters North", ylab = "Meters West"),
## flld.c+     plot.axes = { axis(1, seq(100, 800, by = 100))
## flld.c+                   axis(2, seq(100, 600, by = 100)) },
## flld.c+     key.title = title(main = "Height\n(meters)"),
## flld.c+     key.axes = axis(4, seq(90, 190, by = 10)))  # maybe also asp = 1

## 
## flld.c> mtext(paste("filled.contour(.) from", R.version.string),
## flld.c+       side = 1, line = 4, adj = 1, cex = .66)
## 
## flld.c> # Annotating a filled contour plot
## flld.c> a <- expand.grid(1:20, 1:20)
## 
## flld.c> b <- matrix(a[,1] + a[,2], 20)
## 
## flld.c> filled.contour(x = 1:20, y = 1:20, z = b,
## flld.c+                plot.axes = { axis(1); axis(2); points(10, 10) })

## 
## flld.c> ## Persian Rug Art:
## flld.c> x <- y <- seq(-4*pi, 4*pi, len = 27)
## 
## flld.c> r <- sqrt(outer(x^2, y^2, "+"))
## 
## flld.c> filled.contour(cos(r^2)*exp(-r/(2*pi)), axes = FALSE)

## 
## flld.c> ## rather, the key *should* be labeled:
## flld.c> filled.contour(cos(r^2)*exp(-r/(2*pi)), frame.plot = FALSE,
## flld.c+                plot.axes = {})

команда help это помощник в R на все случаи жизни

help(example)
example(cor)
## 
## cor> var(1:10)  # 9.166667
## [1] 9.166667
## 
## cor> var(1:5, 1:5) # 2.5
## [1] 2.5
## 
## cor> ## Two simple vectors
## cor> cor(1:10, 2:11) # == 1
## [1] 1
## 
## cor> ## Correlation Matrix of Multivariate sample:
## cor> (Cl <- cor(longley))
##              GNP.deflator       GNP Unemployed Armed.Forces Population
## GNP.deflator    1.0000000 0.9915892  0.6206334    0.4647442  0.9791634
## GNP             0.9915892 1.0000000  0.6042609    0.4464368  0.9910901
## Unemployed      0.6206334 0.6042609  1.0000000   -0.1774206  0.6865515
## Armed.Forces    0.4647442 0.4464368 -0.1774206    1.0000000  0.3644163
## Population      0.9791634 0.9910901  0.6865515    0.3644163  1.0000000
## Year            0.9911492 0.9952735  0.6682566    0.4172451  0.9939528
## Employed        0.9708985 0.9835516  0.5024981    0.4573074  0.9603906
##                   Year  Employed
## GNP.deflator 0.9911492 0.9708985
## GNP          0.9952735 0.9835516
## Unemployed   0.6682566 0.5024981
## Armed.Forces 0.4172451 0.4573074
## Population   0.9939528 0.9603906
## Year         1.0000000 0.9713295
## Employed     0.9713295 1.0000000
## 
## cor> ## Graphical Correlation Matrix:
## cor> symnum(Cl) # highly correlated
##              GNP. GNP U A P Y E
## GNP.deflator 1                 
## GNP          B    1            
## Unemployed   ,    ,   1        
## Armed.Forces .    .     1      
## Population   B    B   , . 1    
## Year         B    B   , . B 1  
## Employed     B    B   . . B B 1
## attr(,"legend")
## [1] 0 ' ' 0.3 '.' 0.6 ',' 0.8 '+' 0.9 '*' 0.95 'B' 1
## 
## cor> ## Spearman's rho  and  Kendall's tau
## cor> symnum(clS <- cor(longley, method = "spearman"))
##              GNP. GNP U A P Y E
## GNP.deflator 1                 
## GNP          B    1            
## Unemployed   ,    ,   1        
## Armed.Forces          . 1      
## Population   B    B   ,   1    
## Year         B    B   ,   1 1  
## Employed     B    B   .   B B 1
## attr(,"legend")
## [1] 0 ' ' 0.3 '.' 0.6 ',' 0.8 '+' 0.9 '*' 0.95 'B' 1
## 
## cor> symnum(clK <- cor(longley, method = "kendall"))
##              GNP. GNP U A P Y E
## GNP.deflator 1                 
## GNP          B    1            
## Unemployed   .    .   1        
## Armed.Forces            1      
## Population   B    B   .   1    
## Year         B    B   .   1 1  
## Employed     *    *   .   + + 1
## attr(,"legend")
## [1] 0 ' ' 0.3 '.' 0.6 ',' 0.8 '+' 0.9 '*' 0.95 'B' 1
## 
## cor> ## How much do they differ?
## cor> i <- lower.tri(Cl)
## 
## cor> cor(cbind(P = Cl[i], S = clS[i], K = clK[i]))
##           P         S         K
## P 1.0000000 0.9802390 0.9572562
## S 0.9802390 1.0000000 0.9742171
## K 0.9572562 0.9742171 1.0000000
## 
## cor> ## cov2cor() scales a covariance matrix by its diagonal
## cor> ##           to become the correlation matrix.
## cor> cov2cor # see the function definition {and learn ..}
## function (V) 
## {
##     p <- (d <- dim(V))[1L]
##     if (!is.numeric(V) || length(d) != 2L || p != d[2L]) 
##         stop("'V' is not a square numeric matrix")
##     Is <- sqrt(1/diag(V))
##     if (any(!is.finite(Is))) 
##         warning("diag(.) had 0 or NA entries; non-finite result is doubtful")
##     r <- V
##     r[] <- Is * V * rep(Is, each = p)
##     r[cbind(1L:p, 1L:p)] <- 1
##     r
## }
## <bytecode: 0x7fed7e4ca4d8>
## <environment: namespace:stats>
## 
## cor> stopifnot(all.equal(Cl, cov2cor(cov(longley))),
## cor+           all.equal(cor(longley, method = "kendall"),
## cor+             cov2cor(cov(longley, method = "kendall"))))
## 
## cor> ##--- Missing value treatment:
## cor> C1 <- cov(swiss)
## 
## cor> range(eigen(C1, only.values = TRUE)$values) # 6.19        1921
## [1]    6.191249 1921.562488
## 
## cor> ## swM := "swiss" with  3 "missing"s :
## cor> swM <- swiss
## 
## cor> colnames(swM) <- abbreviate(colnames(swiss), min=6)
## 
## cor> swM[1,2] <- swM[7,3] <- swM[25,5] <- NA # create 3 "missing"
## 
## cor> ## Consider all 5 "use" cases :
## cor> (C. <- cov(swM)) # use="everything"  quite a few NA's in cov.matrix
##           Frtlty Agrclt Exmntn     Eductn Cathlc    Infn.M
## Frtlty 156.04250     NA     NA -79.729510     NA 15.156193
## Agrclt        NA     NA     NA         NA     NA        NA
## Exmntn        NA     NA     NA         NA     NA        NA
## Eductn -79.72951     NA     NA  92.456059     NA -2.781684
## Cathlc        NA     NA     NA         NA     NA        NA
## Infn.M  15.15619     NA     NA  -2.781684     NA  8.483802
## 
## cor> try(cov(swM, use = "all")) # Error: missing obs...
## 
## cor> C2 <- cov(swM, use = "complete")
## 
## cor> stopifnot(identical(C2, cov(swM, use = "na.or.complete")))
## 
## cor> range(eigen(C2, only.values = TRUE)$values) # 6.46   1930
## [1]    6.462385 1930.505982
## 
## cor> C3 <- cov(swM, use = "pairwise")
## 
## cor> range(eigen(C3, only.values = TRUE)$values) # 6.19   1938
## [1]    6.194469 1938.033663
## 
## cor> ## Kendall's tau doesn't change much:
## cor> symnum(Rc <- cor(swM, method = "kendall", use = "complete"))
##        F A Ex Ed C I
## Frtlty 1            
## Agrclt   1          
## Exmntn . . 1        
## Eductn . . .  1     
## Cathlc     .     1  
## Infn.M             1
## attr(,"legend")
## [1] 0 ' ' 0.3 '.' 0.6 ',' 0.8 '+' 0.9 '*' 0.95 'B' 1
## 
## cor> symnum(Rp <- cor(swM, method = "kendall", use = "pairwise"))
##        F A Ex Ed C I
## Frtlty 1            
## Agrclt   1          
## Exmntn . . 1        
## Eductn . . .  1     
## Cathlc     .     1  
## Infn.M .           1
## attr(,"legend")
## [1] 0 ' ' 0.3 '.' 0.6 ',' 0.8 '+' 0.9 '*' 0.95 'B' 1
## 
## cor> symnum(R. <- cor(swiss, method = "kendall"))
##                  F A Ex Ed C I
## Fertility        1            
## Agriculture        1          
## Examination      . . 1        
## Education        . . .  1     
## Catholic             .     1  
## Infant.Mortality .           1
## attr(,"legend")
## [1] 0 ' ' 0.3 '.' 0.6 ',' 0.8 '+' 0.9 '*' 0.95 'B' 1
## 
## cor> ## "pairwise" is closer componentwise,
## cor> summary(abs(c(1 - Rp/R.)))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## 0.00000 0.00000 0.04481 0.09573 0.15214 0.53941 
## 
## cor> summary(abs(c(1 - Rc/R.)))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## 0.00000 0.02021 0.08482 0.50675 0.16192 7.08509 
## 
## cor> ## but "complete" is closer in Eigen space:
## cor> EV <- function(m) eigen(m, only.values=TRUE)$values
## 
## cor> summary(abs(1 - EV(Rp)/EV(R.)) / abs(1 - EV(Rc)/EV(R.)))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.8942  1.1464  1.2452  1.3732  1.3722  2.3265

Последний вопрос: где выход?

help(q) 
# savehistory('history1')
# save.image('1')
# q()